package server.main.config.springsecurity.config;

import com.alibaba.fastjson.JSON;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


@Component
public class MyAuthenticationFailHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        Map<String, Object> map = new HashMap<>();
        map.put("code",300);
        map.put("msg",e.getMessage()+"请校验用户和密码！");
        if (e instanceof LockedException) {
            map.put("msg", "账户被锁定，登陆失败！");
        } else if (e instanceof BadCredentialsException) {
            map.put("msg", "账户名或密码输入错误，登陆失败！");
        } else if (e instanceof DisabledException) {
            map.put("msg", "账户被禁用，登陆失败！");
        } else if (e instanceof AccountExpiredException) {
            map.put("msg", "账户已过期，登陆失败！");
        } else if (e instanceof CredentialsExpiredException) {
            map.put("msg", "密码已过期，登陆失败！");
        } else {
            map.put("msg", "登陆失败！");
        }
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        PrintWriter out = httpServletResponse.getWriter();
        out.write(JSON.toJSONString(map));
        out.flush();
        out.close();

        getCookieMsg(httpServletRequest);

    }

    private void getCookieMsg(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (null == cookies || cookies.length < 1) {
            System.out.println("------> Cookie已全部清除！");
        } else {
            System.out.println("---Cookie---> " + JSON.toJSONString(cookies));
        }
    }


}
